package com.yhgarden.bbs.service.impl.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhgarden.bbs.entity.system.Menu;
import com.yhgarden.bbs.entity.system.Role;
import com.yhgarden.bbs.entity.system.SystemUser;
import com.yhgarden.bbs.entity.vo.systemUser.SystemUserRoleMenuVo;
import com.yhgarden.bbs.entity.vo.systemUser.SystemUserRolesVo;
import com.yhgarden.bbs.entity.vo.user.UserLoginVo;
import com.yhgarden.bbs.mapper.system.MenuMapper;
import com.yhgarden.bbs.mapper.system.RoleMapper;
import com.yhgarden.bbs.mapper.system.SystemUserMapper;
import com.yhgarden.bbs.model.constants.YhbbsConstants;
import com.yhgarden.bbs.model.enums.StatusCode;
import com.yhgarden.bbs.model.helper.LoginHelper;
import com.yhgarden.bbs.model.helper.Pager;
import com.yhgarden.bbs.model.helper.SortPointer;
import com.yhgarden.bbs.model.response.BaseResponse;
import com.yhgarden.bbs.service.api.system.MenuService;
import com.yhgarden.bbs.service.api.system.SystemUserService;
import com.yhgarden.bbs.utils.security.AESUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

import static com.yhgarden.bbs.utils.captcha.CaptchaExtend.validateCaptcha;

@Service
public class SystemUserServiceImpl implements SystemUserService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public BaseResponse createOrUpdate(HttpSession session, SystemUser systemUser) throws Exception {
        SystemUserRolesVo systemUserRolesVo = (SystemUserRolesVo) session.getAttribute(YhbbsConstants.SYSTEM_USER_SESSION_KEY);
        SystemUser sessionUser = systemUserRolesVo.getSystemUser();
        String userId = sessionUser.getId();
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        //从session中获取密钥
        String publicKey = (String) session.getAttribute(YhbbsConstants.PUBLIC_KEY);
        //判断密钥是否过期
        if(publicKey == null){
            response = new BaseResponse(StatusCode.PUBLIC_KEY_EXPIRED);
            return response;
        }
        if(systemUser.getId() == null){
            //判断用户是否已经存在
            String account = systemUser.getAccount();
            SystemUser record = systemUserMapper.getByAccount(account);
            if(record != null){
                response = new BaseResponse(StatusCode.USER_HAS_BEEN_EXIT);
                return response;
            }
            //解密前端数据
            String passwordDec = AESUtil.aesDecrypt(systemUser.getPassword(),publicKey);
            //MD5加密存入数据库
            String passwordMd5 = DigestUtils.md5Hex(passwordDec);
            systemUser.setPassword(passwordMd5);
            String uuid = UUID.randomUUID().toString();
            systemUser.setId(uuid);
            sessionUser.setCreatedBy(userId);
            systemUserMapper.create(systemUser);
        }else {
            //解密前端数据
            String passwordDec = AESUtil.aesDecrypt(systemUser.getPassword(),publicKey);
            //MD5加密存入数据库
            String passwordMd5 = DigestUtils.md5Hex(passwordDec);
            systemUser.setPassword(passwordMd5);
            sessionUser.setUpdatedBy(userId);
            systemUserMapper.update(systemUser);
        }
        response.setData(systemUser);
        return response;
    }


    @Override
    public BaseResponse login(HttpServletRequest request, UserLoginVo userLoginVo) throws Exception {
        HttpSession session = request.getSession();
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        //判断验证码是否正确
        if( !validateCaptcha(request,userLoginVo.getCaptcha())){
            response = new BaseResponse(StatusCode.RANDOM_CODE_ERROR);
            return response;
        }
        //从session中获取密钥
        String publicKey = (String) session.getAttribute(YhbbsConstants.PUBLIC_KEY);
        //判断密钥是否过期
        if(publicKey == null || !userLoginVo.getPublicKey().equals(publicKey)){
            response = new BaseResponse(StatusCode.PUBLIC_KEY_EXPIRED);
            return response;
        }
        //解密前端数据
        String passwordDec = AESUtil.aesDecrypt(userLoginVo.getPassword(),publicKey);
        //MD5加密
        String passwordMd5 = DigestUtils.md5Hex(passwordDec);
        String account = userLoginVo.getAccount();
        SystemUser systemUser = systemUserMapper.getByAccount(account);
        if(systemUser == null){
            response = new BaseResponse(StatusCode.USER_NOT_FOUND);
            return response;
        }
        if(!passwordMd5.equals(systemUser.getPassword())){
            response = new BaseResponse(StatusCode.PASSWORD_INCORRECT);
            return response;
        }
        String userId = systemUser.getId();
        //获取用户角色
        List<Role> roleList = roleMapper.getSystemUserRoles(userId);
        SystemUserRolesVo systemUserRolesVo = new SystemUserRolesVo();
        systemUserRolesVo.setSystemUser(systemUser);
        systemUserRolesVo.setRoleList(roleList);
        //将用户信息写入session
        LoginHelper.adminLogin(session, systemUserRolesVo);

        //根据角色获取菜单列表
//        List<Menu> menuList = menuService.getByRolesAndUserId(roleList,userId);
        List<Menu> menuList = menuMapper.getByPid("a9800ce0-b13f-4f06-a3f3-75eec1b100ee");

        SystemUserRoleMenuVo systemUserRoleMenuVo = new SystemUserRoleMenuVo();
        systemUserRoleMenuVo.setSystemUser(systemUser);
        systemUserRoleMenuVo.setRoleList(roleList);
        systemUserRoleMenuVo.setMenuList(menuList);

        response.setData(systemUserRoleMenuVo);
        return response;
    }

    @Override
    public BaseResponse judgeLogin(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Boolean result = false;
        if(session != null && session.getAttribute(YhbbsConstants.SYSTEM_USER_SESSION_KEY) != null){
            result = true;
        }
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse getById(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        SystemUser systemUser = systemUserMapper.getById(id);
        response.setData(systemUser);
        return response;
    }


    @Override
    public BaseResponse getByIdMoreDetail(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        SystemUser systemUser = systemUserMapper.getByIdMoreDetail(id);
        response.setData(systemUser);
        return response;
    }


    @Override
    public BaseResponse query(SystemUser systemUser) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = systemUser.getPager();
        SortPointer sortPointer = systemUser.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<SystemUser> systemUserList = systemUserMapper.query(systemUser,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<SystemUser>(systemUserList);
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse queryForList(SystemUser systemUser) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = systemUser.getPager();
        SortPointer sortPointer = systemUser.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<SystemUser> systemUserList = systemUserMapper.queryForList(systemUser,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<SystemUser>(systemUserList);
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse delete(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        systemUserMapper.delete(id);
        return response;
    }

}
